import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:library_base/constant/constant.dart';
import 'package:library_base/entities/enum_entity.dart';
import 'package:library_base/entities/suppliers_shops_list_entity.dart';
import 'package:library_base/ext/bool_ext.dart';
import 'package:library_base/ext/double_ext.dart';
import 'package:library_base/ext/list_ext.dart';
import 'package:library_base/ext/theme_data_ext.dart';
import 'package:library_base/global/multi_language.dart';
import 'package:library_base/res/decoration.dart';
import 'package:library_base/res/dividing_line.dart';
import 'package:library_base/res/edge.dart';
import 'package:library_base/res/gaps.dart';
import 'package:library_base/res/styles.dart';
import 'package:library_base/utils/get_util.dart';
import 'package:library_base/utils/sp_util.dart';
import 'package:library_base/utils/theme_util.dart';
import 'package:library_base/widget/button/gradient_button.dart';
import 'package:library_base/widget/image/local_image.dart';

class GenerateSalesOrderDialog extends StatefulWidget {

  const GenerateSalesOrderDialog({
    Key? key,
  }) : super(key: key);

  @override
  State<GenerateSalesOrderDialog> createState() => _GenerateSalesOrderDialogState();
}

class _GenerateSalesOrderDialogState extends State<GenerateSalesOrderDialog> {

  ///是否激活提交按钮
  var enableSubmit = false;

  ///是否生成销售单
  var isGenerateSalesOrder = true;

  ///供应商所拥有的门店
  late List<SuppliersShopsListEntity> suppliersShopsListEntities;

  ///回调选择的门店
  late Function(SuppliersShopsListEntity?) callBack;

  ///选中的门店
  SuppliersShopsListEntity? suppliersShopsListEntity;

  @override
  void initState() {
    super.initState();
    callBack = Get.arguments['CallBack'];
    suppliersShopsListEntities = Get.arguments['SuppliersShopsListEntities'];
    suppliersShopsListEntity = Get.arguments['suppliersShopsListEntity'];
    if(suppliersShopsListEntity!=null){
      try{
        suppliersShopsListEntity = suppliersShopsListEntities.firstWhere((element) => element.id == suppliersShopsListEntity!.id);
        suppliersShopsListEntity!.isSelected = true;
      }catch(e){
        suppliersShopsListEntity = null;
      }
    }

    if(suppliersShopsListEntities.length == 1){
      suppliersShopsListEntity ??= suppliersShopsListEntities[0];
    }

    enableSubmit = isCanSubmit();
  }
  
  @override
  Widget build(BuildContext context) {
    return Material(
      color: Colors.transparent,
      child: WillPopScope(
          onWillPop: () {
        GetHelper.back();
        return Future.value(false);
      },
      child: GestureDetector(
      onTap: () {},
        child: Container(
          padding: const EdgeInsets.only(bottom: 50),
          width: double.infinity,
          color: Colors.transparent,
          alignment: Alignment.center,
          height: double.infinity,
          child: Row(
            children: [
              SizedBox(width: 0.06.sw),
              Expanded(
                child: Container(
                  decoration: rs8,
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      SizedBox(
                        height: 95.w,
                        width: double.infinity,
                        child: Stack(
                          children: [
                            Container(
                                alignment: Alignment.center,
                                child: Text(MultiLanguage.generateSalesOrder.tr,
                                    style: normalTextColor34)),
                            Positioned(
                              top: 10.w,
                              right: 0,
                              child: GestureDetector(
                                onTap: () => GetHelper.back(),
                                child: Padding(
                                    padding: edgeAll24,
                                    child: LocalImage('common_close',
                                        package: Constant.packLib(), width: 26.w, height: 26.w)),
                              ),
                            )
                          ],
                        ),
                      ),
                      line1,
                      Column(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          gapH36,
                          Container(
                            alignment: Alignment.bottomLeft,
                            padding: edgeLR36,
                            child: Text(MultiLanguage.whetherToGenerateSalesOrder.tr,style: normalTextColor28),
                          ),
                          gapH24,
                          Padding(
                            padding: edgeLR24,
                            child: Row(
                              children: [
                                buildRadioWidget(isGenerateSalesOrder,MultiLanguage.yes.tr),
                                gapW50,
                                buildRadioWidget(!isGenerateSalesOrder,MultiLanguage.no.tr),
                              ],
                            ),
                          ),
                          gapH24,
                          Container(
                            alignment: Alignment.bottomLeft,
                            padding: edgeLR36,
                            child: Text(MultiLanguage.selectStoreAndDeliveryAddress.tr,style: normalTextColor28),
                          ),
                          gapH24,
                          Material(
                            color: Colors.transparent,
                            child: MediaQuery.removePadding(
                            context: context,
                            removeTop: true,
                            removeBottom: true,
                            child: getListWidget())),
                          gapH36,
                          line1,
                          Container(
                            width: double.infinity,
                            height: 125.w,
                            padding: EdgeInsets.symmetric(vertical: 24.w,horizontal: 36.w),
                            child: GradientButton(
                              ThemeUtil.getTheme(),
                              colors: ThemeUtil.getTheme().buttonRight1BgColor(),
                              width: double.infinity,
                              height: double.infinity,
                              text: MultiLanguage.identifyAndSubmit.tr,
                              onPressed: enableSubmit? _submit:null,
                            ),
                          )
                        ],
                      ),
                    ],
                  ),
                ),
              ),
              SizedBox(width: 0.06.sw),
            ],
          ),
        ),
      )),
    );
  }

  void _submit(){
    callBack.call(suppliersShopsListEntity);
  }

  Widget buildRadioWidget(bool isSelected,String data){
    return GestureDetector(
      onTap: (){
        isGenerateSalesOrder = !isGenerateSalesOrder;
        if(!isGenerateSalesOrder){
          for(int i = 0;i<suppliersShopsListEntities.length;i++){
            suppliersShopsListEntities[i].isSelected = false;
          }
          suppliersShopsListEntity = null;
        }
        enableSubmit = isCanSubmit();
        setState(() {});
      },
      child: Container(
        color: Colors.transparent,
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            LocalImage(isSelected ? 'common_radio_choosed_flag' : 'common_radio_choose_flag', package: Constant.packLib(), width: 34.r, height: 34.r),
            gapW8,
            Text(data,style: normalTextColor28),
          ],
        ),
      ),
    );
  }

  buildItem(
      {GestureTapCallback? onTap, required String title, required String hint, String? content}) {
    return Row(children: [
      Expanded(
          flex: 2, child: Text(title, style: normalTextColor28, textAlign: TextAlign.end)),
      Gaps.hGap24,
      Expanded(
          flex: 7,
          child: GestureDetector(
            onTap: onTap,
            child: Container(
                padding: edgeAll24,
                decoration: BoxDecoration(
                    borderRadius: const BorderRadius.all(Radius.circular(30.0)),
                    border:
                    Border.all(color: ThemeUtil.getTheme().secondaryTextColor(), width: 1.0)),
                child: Row(children: [
                  Expanded(
                      child: Text(content == null || content.isEmpty ? hint : content,
                          style: content == null || content.isEmpty
                              ? TextStyles.textSecondary28
                              : normalTextColor28)),
                  LocalImage('common_grey_rightward_arrow',
                      package: Constant.packLib(), width: 20.w, height: 20.w),
                ])),
          )),
      gapW24,
    ]);
  }


  ///确定过滤
  determine() {
    GetHelper.back();
  }

  ///判断是否自家的服务器标准的json格式,默认是有code和data即可
  bool isStandardJson(Map<dynamic, dynamic> data) {
    return data.containsKey('code') && data.containsKey('data') && data.containsKey('msg');
  }

  ///是否已经满足提交条件
  bool isCanSubmit(){
    if(isGenerateSalesOrder){
        return !(suppliersShopsListEntity == null);
    }
    return true;
  }

  ///构建Item
  _buildItem() {
    return suppliersShopsListEntities.buildItem((index, element) {
      return GestureDetector(
        onTap: (){
          if(isGenerateSalesOrder){
            for(int i  = 0;i<suppliersShopsListEntities.length;i++){
              suppliersShopsListEntities[i].isSelected = false;
            }
            element.isSelected = true;
            suppliersShopsListEntity = element;
            enableSubmit = isCanSubmit();
            setState(() {});
          }
        },
        child: Container(
          margin: edgeLR36,
          decoration: element.isSelected?rs8_2:rs8_1,
          child: Stack(
            children: [
              Padding(
                padding: edgeAll18,
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Row(
                      children: [
                        Expanded(child: Text(element.shopName,style: getTextStyle(element.isSelected))),
                        Expanded(child: Text("${MultiLanguage.purchasePrice.tr}${getPriceModelStr(element)}",style: getTextStyle(element.isSelected))),
                      ],
                    ),
                    gapH18,
                    Container(
                        alignment: Alignment.centerLeft,
                        child: Text(element.orderTakerName,style: getTextStyle(element.isSelected))),
                    gapH18,
                    Container(
                        alignment: Alignment.centerLeft,
                        child: Text(element.address,style: getTextStyle(element.isSelected))),
                  ],
                ),
              ),
              Positioned(
                top: 0,
                right: 0,
                child: Visibility(
                  visible: element.isSelected,
                    child: LocalImage('common_choosed_flag', package: Constant.packLib(), width: 67.r, height: 59.r)),
              ),
            ],
          ),
        ),
      );
    }, dividingLine: () {
      return gapH18;
    },divideType: DivideType.MIDDLE);
  }

  Widget getListWidget(){
    if(suppliersShopsListEntities.length<=3){
      return Column(
        mainAxisSize: MainAxisSize.min,
        children: _buildItem(),
      );
    }else{
      return  SizedBox(
        height: 0.4.sh,
        width: double.infinity,
        child: ListView(
          children: _buildItem(),
        ),
      );
    }
  }

  ///返回计价模式字符串
  String getPriceModelStr(SuppliersShopsListEntity suppliersShopsListEntity){
    if(suppliersShopsListEntity.priceModel == "FIXED"){
      return "+${suppliersShopsListEntity.amount.remoteAsLocalUnit(ServiceUnit.KG.name)}${MultiLanguage.yuan.tr}/${SPUtil.isJin.unitStrZh()}";
    }else if(suppliersShopsListEntity.priceModel == "RATIO"){
      return "+${suppliersShopsListEntity.amount.toStringAsFixed(2)}%";
    }
    return "";
  }

  TextStyle getTextStyle(bool isSelected){
    return isSelected? fourthTextColor26: sixthTextColor26;
  }

}
